package com.reef.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.reef.dao.DetailedRepository;
import com.reef.dto.DetailedDto;
import com.reef.entity.Detailed;
import com.reef.service.DetailedService;


@Service
public class DetailedServiceImpl implements DetailedService{
	@Autowired
	private DetailedRepository deRepository;

	public Detailed addDetailed(Detailed de) {
		// TODO Auto-generated method stub
		return deRepository.save(de);
	}

	public int updateTime(String endtime, int did) {
		// TODO Auto-generated method stub
		return deRepository.updateTime(endtime, did);
	}

	public Page<Detailed> findByDetailedCondition(DetailedDto dDto, Pageable pageable) {
		Specification<Detailed> spec = ddGteSpec(dDto);
		return deRepository.findAll(spec, pageable);
	}
	/**
	 * 封装
	 */
	public Specification<Detailed> ddGteSpec(final DetailedDto dDto) {
		return new Specification<Detailed>() {

			public Predicate toPredicate(Root<Detailed> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				Predicate p = criteriaBuilder.conjunction();
				List<Expression<Boolean>> list = p.getExpressions();
				if (dDto.getDname()!=null && dDto.getDname()!="") {
					list.add(criteriaBuilder.equal(root.get("dname").as(String.class),dDto.getDname() ));
				}
				if (dDto.getStatus()!=null && dDto.getStatus()!="") {
					list.add(criteriaBuilder.equal(root.get("status").as(String.class), dDto.getStatus()));
				}
				if (dDto.getStartentertime()!=null && dDto.getStartentertime()!="") {
					list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("entertime").as(String.class), dDto.getStartentertime()));
				}
				if (dDto.getEndentertime()!=null && dDto.getEndentertime()!="") {
					list.add(criteriaBuilder.lessThanOrEqualTo(root.get("entertime").as(String.class), dDto.getEndentertime()));
				}
				if (dDto.getStartleavetime()!=null && dDto.getStartleavetime()!="") {
					list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("leavetime").as(String.class), dDto.getStartleavetime()));
				}
				if (dDto.getEndleavetime()!=null && dDto.getEndleavetime()!="") {
					list.add(criteriaBuilder.lessThanOrEqualTo(root.get("leavetime").as(String.class), dDto.getEndleavetime()));
				}
				return p;
			}
		};
		
	}



	
}